package com.chao.exception;

import com.chao.model.ResponseVO;
import com.chao.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Luck Chao
 * @Date: 2021/12/09
 */
@Slf4j
@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {

    public GlobalExceptionHandler() {
        log.info("\033[32;1m" + "================ [全局异常处理] Start Success ======================" + "\033[0m");
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseVO exceptionHandler(HttpServletRequest req, Exception e) {

        // @Valid-@NotNull 拦截处理
        if (e instanceof MethodArgumentNotValidException) {
            BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            if (bindingResult.hasErrors()) {
                return ResultUtils.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
            }
        }

        log.error("捕获全局异常！原因是:",e);
        return ResultUtils.error(e.getMessage());
    }

    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ResponseVO businessExceptionHandler(HttpServletRequest req, Exception e) {

        log.error("捕获全局异常！原因是:",e);
        return ResultUtils.error(e.getMessage());
    }




}
